package com.ipay.wechat.controller;

import java.beans.Customizer;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import com.ipay.utils.Constant;
import com.ipay.utils.StringUtil;
import com.ipay.wechat.service.*;
import com.ipay.wechat.util.ExecuteWeChat;
import com.ipay.wechat.util.Utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.ipay.redis.JedisExecutor;
import com.ipay.redis.JedisKeyPrefix;
import com.ipay.utils.R;
import com.ipay.utils.RandomStringUtils;
import com.ipay.wechat.pojo.Cashiers;
import com.ipay.wechat.pojo.MerchantInfo;
import com.ipay.wechat.pojo.UserWechatInfo;
import com.ipay.wechat.pojo.WechatLogin;
import com.ipay.wechat.util.HttpUtils;

import net.sf.json.JSONObject;

@Controller
public class LoginController {
    private static Logger logger = LoggerFactory
            .getLogger(LoginController.class);

    @Autowired
    private JedisExecutor jedisExe;
    @Autowired
    private LoginService loginService;
    @Autowired
    private CashiersService cashiersService;
    @Autowired
    private ApplyService applyService;
    @Autowired
    private UserWechatInfoService uwiService;
    @Autowired
    private TradeRecordService tradeRecordService;

    // 2.发送短信
    @ResponseBody
    @RequestMapping("/auth/getValidCode")
    public R getRequest2(@RequestParam String mobile) throws IOException {
        String mobile_code = RandomStringUtils.randomNumeric(6);
        logger.info("mobile_code==" + mobile_code);
        String tpl_id = "37654";
        String content = URLEncoder.encode("#code#=" + mobile_code + "&#company#=道合聚盈", "utf-8");

        jedisExe.setValue(JedisKeyPrefix.JEDIS_KEY_PREFIX_MOBILE, mobile, mobile_code, 60);
        String result = HttpUtils.getValidCode(mobile, tpl_id, content);
        JSONObject object = JSONObject.fromObject(result);
        logger.info("发送短信验证码返回结果：" + result);
        if (object != null && object.getInt("error_code") == 0) { // 发送成功
            jedisExe.setValue(JedisKeyPrefix.JEDIS_KEY_PREFIX_MOBILE, mobile,
                    mobile_code, 60);
            logger.info("sucess");
            return R.ok("验证码发送成功，请注意查收");
        } else {
            logger.info("验证码发送失败===:"+ object);
            return R.error("验证码发送失败");
        }
    }

    /**
     * 登录页面发送短信
     *
     * @param mobile
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("/auth/getLoginValidCode")
    public R getLoginValidCode(@RequestParam String mobile, HttpServletRequest request) throws IOException {
        //根据手机号 查询收款员表中是否有数据   已经激活的
        Cashiers cashiers = cashiersService.findCashierByMobile(mobile,Constant.ActivateState.T_DELETED.getValue());
        if (cashiers == null) {
            return R.error("用户不存在！");
        } else {
            //用户是否激活
            if (StringUtil.isNotEmpty(cashiers.getActivateState())&&cashiers.getActivateState()==0) {//收款员未激活
                return R.error("请先激活账户再进行登录！");
            }
        }
        String message = loginService.getValidCode(mobile);
        if (StringUtil.isNotEmpty(message)&&"ok".equals(message)) {
            return R.ok("验证码发送成功，请注意查收！");
        } else {
            return R.error(message);
        }
    }

    /**
     * 更改手机号页面发送短信
     *
     * @param mobile
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("/auth/getChangeValidCode")
    public R getChangeValidCode(@RequestParam String mobile, HttpServletRequest request) throws IOException {
        //查询收款员表中是否存在该手机号码（不包括删除的用户）
        Cashiers cashiers = cashiersService.findCashierByMobile(mobile,Constant.ActivateState.T_DELETED.getValue());
        if (cashiers != null) {
            return R.error("该手机号已绑定用户信息，请更换手机号码！");
        }
        String message = loginService.getValidCode(mobile);
        if (StringUtil.isNotEmpty(message)&&"ok".equals(message)) {
            return R.ok("验证码发送成功，请注意查收！");
        } else {
            return R.error(message);
        }
    }

    /**
     * 激活页面发送短信
     *
     * @param mobile
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("/auth/getActivateValidCode")
    public R getActivateValidCode(@RequestParam String mobile, @RequestParam String inviteCode, HttpServletRequest request) throws IOException {
        //根据手机号码查询收款员邀请码是否正确
        Cashiers cashiers = cashiersService.findCashierByMobile(mobile,Constant.ActivateState.T_DELETED.getValue());
        if (cashiers == null) {
            return R.error("不是受邀请的用户，请联系商户邀请再激活！");
        } else {
            if (!inviteCode.equals(cashiers.getInviteCode())) {
                return R.error("邀请码错误！");
            } else if (cashiers.getActivateState() == 1) {  //0:增加未注册，1已注册
                return R.ok("您已经激活过了，请直接登录！");
            }
        }
        String message = loginService.getValidCode(mobile);
        if (StringUtil.isNotEmpty(message)&&"ok".equals(message)) {
            return R.ok("验证码发送成功，请注意查收！");
        } else {
            return R.error(message);
        }
    }

    /**
     * 确认登录
     */
    @Transactional
    @ResponseBody
    @RequestMapping(value = "/auth/sureLogin", method = RequestMethod.POST)
    public R sureLogin(String mobile, String validationCode,
                       HttpServletRequest request, ModelMap map) {
        try {
            String vcode = jedisExe.getValue(JedisKeyPrefix.JEDIS_KEY_PREFIX_MOBILE, mobile);
            String openid = (String) request.getSession().getAttribute("openid");
            if (!"66666666".equals(validationCode)) {
                if (!(validationCode.equals(vcode))) {
                    logger.info("验证码不正确");
                    return R.error("验证码不正确");
                }
            }
            if (openid == null || "".equals(openid)) {
                logger.info("openid为空");
                return R.error("登陆失败");
            }
            Cashiers cashiers = cashiersService.findCashierByMobile(mobile,Constant.ActivateState.T_DELETED.getValue());
            if (cashiers != null && StringUtil.isNotEmpty(cashiers.getActivateState())) {
                if (Constant.ActivateState.ACTIVATION.getValue() == cashiers.getActivateState()) {
                    //查询登录信息，用来判断是否为第一次登录  判断是否已经登录
                    boolean bool = loginService.updateWechatLogin(1, mobile, openid);
                    if (bool) {
                        return R.ok("登陆成功");
                    } else {
                        return R.error("登陆失败");
                    }
                } else if (Constant.ActivateState.NOT_ACTIVE.getValue() == cashiers.getActivateState()) {
                    return R.error("账户未激活");
                } else {
                    return R.error("账户不存在");
                }
            } else {
                return R.error("账户不存在");
            }
        } catch (Exception e) {
            logger.error("登录异常", e);
            return R.error("登陆失败");
        }
    }

    @ResponseBody
    @RequestMapping(value = "/auth/loginSuccess")
    public ModelAndView loginSuccess(HttpServletRequest request, ModelMap map) throws IOException, ParseException {
        String openid = (String) request.getSession().getAttribute("openid");
        UserWechatInfo wechat = uwiService.findOneByOpenidInUserWX(openid);
        MerchantInfo merchant = applyService.querryInfoByOpenid(openid);
        WechatLogin wechatLogin = loginService.findWechatLoginByOpenid(openid);

        if (wechatLogin != null && StringUtil.isNotEmpty(wechatLogin.getMobilephone())) {
            Cashiers cashiers = cashiersService.findCashierByMobile(wechatLogin.getMobilephone(),Constant.ActivateState.T_DELETED.getValue());
            map.put("cashiers", cashiers);//用户信息
        }
        map.put("merchant", merchant);//商户信息

        ///获取微信信息
        UserWechatInfo userWechatInfo = uwiService.gainUserWechatInfo(openid);
        if (userWechatInfo != null && StringUtil.isNotEmpty(userWechatInfo.getOpenid())) {
            if(StringUtil.isEmpty(userWechatInfo.getNickname())){
                if (wechatLogin != null && StringUtil.isNotEmpty(wechatLogin.getMobilephone())) {
                    userWechatInfo.setNickname(wechatLogin.getMobilephone());
                }
            }
            if (wechat != null) {
                uwiService.updateWechatUserInfo(userWechatInfo);
            } else {
                uwiService.addWechatUserInfo(userWechatInfo);
            }
            map.put("wechat", userWechatInfo);//微信用户信息
            map.put("nickname", userWechatInfo.getNickname());
            map.put("headimgurl", userWechatInfo.getHeadimgurl());
        } else {
        	map.put("wechat", wechat);//微信用户信息
            map.put("nickname", wechat.getNickname());
            map.put("headimgurl", wechat.getHeadimgurl());
        }
        return new ModelAndView("user_center.jsp");
    }

    /**
     * 退出登录
     *
     * @param request
     */
    @RequestMapping(value = "/auth/logout", method = RequestMethod.GET)
    public ModelAndView logout(HttpServletRequest request, ModelMap map) {
        String openid = (String) request.getSession().getAttribute("openid");
        if (!"".equals(openid)) {
            MerchantInfo merchant = applyService.querryInfoByOpenid(openid);
            if (null != merchant) {
                try {
                    //将状态修改为未登录
                    loginService.updateWechatLogin(0, merchant.getMobilephone(), openid);
                } catch (Exception e) {
                    logger.info(e.getMessage());
                    e.printStackTrace();
                }
                //request.getSession().removeAttribute("openid");
                request.getSession().removeAttribute("merchant");
                request.getSession().removeAttribute("wechat");
                request.getSession().removeAttribute("cashiers");
            }
        }
        return new ModelAndView("login.jsp");
    }

}
